package com.sz.pc.aop;

import java.util.Arrays;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.feilong.core.Validator;
import com.sz.pc.entity.model.ResultModel;
import com.sz.pc.entity.model.ResultModelEnum;
import com.sz.pc.entity.model.constants.Constants;
import com.sz.pc.entity.tb.SysWebLog;
import com.sz.pc.service.interfs.log.ISysWebLogService;
import com.sz.pc.utils.ServletUtil;


@Aspect
@Component
public class WebLogAop {

    private Logger logger = LoggerFactory.getLogger(WebLogAop.class);

    @Resource
    private ISysWebLogService webLogService;

    @Pointcut(value = "execution(public * com.sz.pc.controller..*.*(..))")
    private void webLog() {

    }
    
    ThreadLocal<Long> startTime = new ThreadLocal<Long>();
    ThreadLocal<Integer> logId = new ThreadLocal<Integer>();


    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String methodToUse = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature()
                .getName();
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info(
                "CLASS_METHOD : " +methodToUse );
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
        String methodName = joinPoint.getSignature().getName();
        doWebLog(methodName, Arrays.toString(joinPoint.getArgs()));
        // 省略日志记录内容
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint,Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("RESPONSE : " + ret);
        long timeUse = System.currentTimeMillis() - startTime.get();
        logger.info("SPEND TIME : " + timeUse);
        SysWebLog webLog = new SysWebLog();
        if(ret instanceof ResultModel){
        	if(((ResultModel) ret).getRet() == ResultModelEnum.SUCCESS.getCode())
        	webLog.setStatus(1);
        	webLog.setId(logId.get());
            webLogService.update(webLog,new EntityWrapper<SysWebLog>().where("id={0}", webLog.getId()));
        }
        
       
    }
    

    private void  doWebLog(String method,Object args) {
    	Integer userId = (Integer) ServletUtil.getSession().getAttribute(Constants.CURRENT_USER_ID);
    	if(Validator.isNullOrEmpty(userId)) userId = 0;
    	SysWebLog webLog = new SysWebLog();
        webLog.setSysId(userId);
        String argsStr = args.toString();
        webLog.setMethodArgs(argsStr.length()>200?args.toString().substring(0,200):argsStr);
        webLog.setMethod(method);
        webLog.setOperateTime(new Date());
        webLog.setStatus(0);
        webLog.setOperateIp(ServletUtil.getIpAddr());
        webLogService.insert(webLog);
        logId.set(webLog.getId());
    }


}
